import { getSearchResultAPI, getSuggesAPI } from '@/api/scarch';
import { AppDispatch } from '../reducer';
import { searchActionType } from '../reducer/search';

/** 获取联想建议（自动补全）Action */
export function getSuggesAction(keyWord: string) {
  return async (dispatch: AppDispatch) => {
    const res = await getSuggesAPI(keyWord);
    // console.log(res);
    dispatch({ type: 'search/saveList', payload: res.data.options });
  };
}

/** 定义清除的action */
export const clearSuggestsAction = (): searchActionType => {
  return {
    type: 'search/clearList',
  };
};

/** 保存历史记录Action */
export const saveHistoriesAction = (payload: string): searchActionType => {
  return {
    type: 'search/saveHistories',
    payload,
  };
};

/** 清除历史记录Action */
export const clearHistoriesAction = (): searchActionType => {
  return {
    type: 'search/clearHistories',
  };
};

/** 获取搜索结果Action */
export function getSearchResultAction(
  keyWord: string,
  page = 1,
  per_page = 10
) {
  return async (dispatch: AppDispatch) => {
    const res = await getSearchResultAPI({ keyWord, page, per_page });
    // console.log(res);
    // 保存搜索结果
    dispatch({ type: 'search/saveResults', payload: res.data.results });
  };
}

/** 清除搜索结果Action */
export const clearResultsAction = (): searchActionType => {
  return {
    type: 'search/clearResults',
  };
};
